package com.edz.from0507to0513apk.Service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestService extends Service {
    private static final String TAG = "TestService";

    public TestService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate()");
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        service.scheduleAtFixedRate(runnable, 5, 20, TimeUnit.SECONDS);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                Socket socket = new Socket("192.168.0.34", 8899);
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(("data on time" + "\n").getBytes("utf-8"));
                outputStream.flush();
            } catch (Exception e) {
                e.getMessage();
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
